package com.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 给定一个整数数组 nums和一个目标值target，请你在该数组中找出和为目标值的那两个整数，并返回他们的数组下标。
 * 你可以假设每种输入只会对应一个答案。但是，数组中同一个元素不能使用两遍。
 *
 */
public class One {
    public int[] twoSum1(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[]{i, j};
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    public int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    public static void main(String[] args) {
        One one = new One();
        int[] ones = new int[]{2,7,11,15,17,19,20,30,23,32};
        int target = 55;
        int times = 10000000;
        long begin = System.currentTimeMillis();
        for (int i = 0; i < times; i++){
            one.twoSum1(ones, target);
        }
        long end1 = System.currentTimeMillis();
        System.out.println(end1 - begin + "");
        for (int i = 0; i < times; i++){
            one.twoSum2(ones, target);
        }
        long end2 = System.currentTimeMillis();
        System.out.println(end2 - end1 + "");
    }
}
